package com.i2863.shiroDemo.util;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@Slf4j
public class AddressUtils {
    /**
     * @param content 请求的参数 格式为：name=xxx&pwd=xxx
     */
    private static String getAddresses(String content) {
        // 调用淘宝API
        String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
        // 取得IP所在的省市区信息
        String returnStr = getResult(urlStr, content);
        if (returnStr != null) {
            String[] temp = returnStr.split(",");
            if (temp.length < 3) {
                return "0";//无效IP，局域网测试
            }
            return returnStr;
        }
        return null;
    }

    /**
     * @param urlStr  请求的地址
     * @param content 请求的参数 格式为：name=xxx&pwd=xxx
     */
    private static String getResult(String urlStr, String content) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();// 新建连接实例
            connection.setConnectTimeout(6000);// 设置连接超时时间，单位毫秒
            connection.setReadTimeout(6000);// 设置读取数据超时时间，单位毫秒
            connection.setDoOutput(true);// 是否打开输出流 true|false
            connection.setDoInput(true);// 是否打开输入流true|false
            connection.setRequestMethod("POST");// 提交方法POST|GET
            connection.setUseCaches(false);// 是否缓存true|false
            connection.connect();// 打开连接端口
            DataOutputStream out = new DataOutputStream(connection
                    .getOutputStream());// 打开输出流往对端服务器写数据
            out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx
            out.flush();// 刷新
            out.close();// 关闭输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder buffer = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            return buffer.toString();
        } catch (IOException e) {
            log.warn("获取IP地址出错,cause by:" + e.getMessage());
        } finally {
            if (connection != null) {
                connection.disconnect();// 关闭连接
            }
        }
        return null;
    }

    public static String getAddressByIp(String ipAddress) {
        String address = "未知";
        if (!"0:0:0:0:0:0:0:1".equals(ipAddress)) {
            String jsonResult = AddressUtils.getAddresses("ip=" + ipAddress);
            if (jsonResult !=null && !StringUtils.isAllEmpty(jsonResult)) {
                JsonObject dataJson = JsonParser.parseString(jsonResult).getAsJsonObject();
                if (dataJson.get("data") != null && !dataJson.get("data").isJsonNull()) {
                    JsonObject data = dataJson.get("data").getAsJsonObject();
                    String country = data.get("country").getAsString();
                    String region = data.get("region").getAsString();
                    String city = data.get("city").getAsString();
                    String county = data.get("county").getAsString();
                    String isp = data.get("isp").getAsString();
                    String area = data.get("area").getAsString();
                    log.info("国家:【{}】，地区:【{}】，省份:【{}】，城市:【{}】，区/县:【{}】，互联网服务提供商:【{}】", country, area, region, city, county, isp);
                    address = country + " " + region + " " + city + " ";
                    log.info(address);
                }
            }
        }
        return address;
    }

/*    // 测试
    public static void main(String[] args) {
        String ip = "106.239.255.250";
        getAddressByIp(ip);
    }*/

}